package sword.offer;

import java.util.*;

/**
 * 从上到下按层打印二叉树，同一层的节点按从左到右的顺序打印，每一层打印到一行。
 * @author 胡宇轩
 * @Email: yuxuan.hu01@bianlifeng.com
 */
public class ThirtyTwo2 {
    // 仔细观察ThirtyTwo解答过程的队列元素变化，就能解答出本题
    class Solution {
        public List<List<Integer>> levelOrder(ThirtyTwo2.TreeNode root) {
            if (Objects.isNull(root)) {
                return new ArrayList<>();
            }
            Queue<ThirtyTwo2.TreeNode> queue = new ArrayDeque<ThirtyTwo2.TreeNode>(){{add(root);}};
            List<List<Integer>> res = new ArrayList<>();
            while(!queue.isEmpty()){
                List<Integer> r = new ArrayList<>();
                int size = queue.size(); // 细节啊~！！！ 或者for循环的时候 给i赋值size i--
                for (int i=0; i<size; i++){
                    ThirtyTwo2.TreeNode curNode = queue.poll();
                    r.add(curNode.val);
                    if(Objects.nonNull(curNode.left)) {queue.add(curNode.left);}
                    if(Objects.nonNull(curNode.right)) {queue.add(curNode.right);}
                }
                res.add(r);
            }
            return res;
        }
    }

    class TreeNode {
        int val;
        ThirtyTwo2.TreeNode left;
        ThirtyTwo2.TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
